package com.itheima.io.utils;

import java.io.*;

public class IOUtils {

    //使用字符流完成文件的复制操作
    public static void copyFileWithCharStream(Reader reader, Writer writer) {
        try {

            //一次读取一个字符数组复制文件
            char[] chs = new char[1024];
            int len = -1;
            while ((len = reader.read(chs)) != -1) {

                writer.write(chs, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            //关闭输入流
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //关闭输出流
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //使用字节流完成文件复制
    public static void copyFileWithByteStream(InputStream in, OutputStream out) {
        try {

            //一次读取一个字节数组
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = in.read(bytes)) != -1) {

                out.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

            //关闭输入流
            if(in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //关闭输出流
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
